package com.uduemc.biso.node.web.component.html;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class BasicUdin {

	@Autowired
	private VelocityEngine velocityEngine;

	// 对固定的组件模板进行缓存
	protected static Map<String, Template> mapTemplate = new HashMap<String, Template>();

	public StringWriter render(String name, String theme, Map<String, Object> mapData) {
		// VelocityContext
		VelocityContext ctx = new VelocityContext(mapData);
		Template t = getTemplate(name, theme);
		StringWriter sw = new StringWriter();
		t.merge(ctx, sw);
		return sw;
	}

	public Template getTemplate(String name, String theme) {
		String key = "VelocityEngine.Template." + name + "." + theme;
		Template template = mapTemplate.get(key);
		if (template == null) {
			template = velocityEngine.getTemplate("templates/component/html/" + name + "/" + theme + ".vm");
			mapTemplate.put(key, template);
		}
//		Template template = velocityEngine.getTemplate("templates/component/html/" + name + "/" + theme + ".vm");
//		if (template == null) {
//			template = velocityEngine.getTemplate("templates/component/html/" + name + "/" + theme + ".vm");
//			redisUtil.set(key, template, 3600 * 24 * 10L);
//		}
		return template;
	}

	public String getCildrenHtml(List<StringBuilder> childrenHtml) {
		if (CollectionUtils.isEmpty(childrenHtml)) {
			return "";
		} else {
			StringBuilder str = new StringBuilder();
			childrenHtml.forEach(str::append);
			return str.toString();
		}
	}

}
